//
//  DBFollowBone.cpp
//  DragonBonesCPP
//
//  Created by DuanHongbo on 15/1/19.
//
//

#include "DBFollowBone.h"

DRAGONBONES_NAMESPACE_BEGIN

DBFollowBone* DBFollowBone::create(float duration, CCArmatureDisplay* armatureNode, const std::string& bone)
{
    DBFollowBone *animate = new (std::nothrow) DBFollowBone();
    animate->init(duration,armatureNode,bone);
    animate->autorelease();
    
    return animate;
}

DBFollowBone::DBFollowBone()
:_armatureNode(nullptr),
_bone(nullptr)
{
    
}

DBFollowBone::~DBFollowBone()
{
    
}

bool DBFollowBone::init(float duration,CCArmatureDisplay* armatureNode, const std::string& bone)
{
    this->_armatureNode = armatureNode;
    this->_boneName = bone;
    if ( ActionInterval::initWithDuration(duration))
    {
        return true;
    }
    return false;
}


DBFollowBone* DBFollowBone::clone() const
{
    // no copy constructor
    auto a = new (std::nothrow) DBFollowBone();
    a->init(this->_duration,this->_armatureNode,this->_boneName);
    a->autorelease();
    return a;
}

void DBFollowBone::update(float t)
{
    updatePos();
}

void DBFollowBone::updatePos()
{
    if(this->_armatureNode && !this->_boneName.empty())
    {
        if(!_bone)
        {
            _bone =  this->_armatureNode->getArmature()->getBone(this->_boneName);
            if(!_bone)
            {
                _boneName.clear();
                return ;
            }
        }

        const auto transform = _armatureNode->getNodeToWorldTransform();
        cocos2d::Vec3 localPoint(_bone->global.x, -_bone->global.y, 0.f);
        cocos2d::Vec2 globalPoint;
        transform.transformPoint(&localPoint);
        globalPoint.set(localPoint.x, localPoint.y);

        _target->setPosition(_target->getParent()->convertToNodeSpace(globalPoint));
    }
}

void DBFollowBone::startWithTarget(Node *target)
{
    ActionInterval::startWithTarget(target);
    updatePos();
}

void DBFollowBone::stop()
{
    ActionInterval::stop();
}

DRAGONBONES_NAMESPACE_END
